Completed
Push — master ( 395a8a...5b5be3 )
by greg
02:00
created

prepare.js ➔ addAbeDictionnary   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
c 0
b 0
f 0
nc 3
nop 3
dl 0
loc 12
rs 9.4285
1
import Handlebars from 'handlebars'
2
3
import {
4
  cmsData
5
  ,config
6
  ,cmsTemplates
7
} from '../../'
8
9
/**
10
 * THIS:
11
<span>{{abe type='text' key='text_visible'}}</span>
12
13
 * BECOME:
14
<span data-abe-text_visible="text_visible" >{{abe type='text' key='text_visible'}}</span>
15
16
 * @param {[type]} template [description]
17
 */
18
export function addAbeDataAttrForHtmlTag(template) {
19
  var match
20
  while (match = cmsData.regex.abePattern.exec(template)) {
21
    var getattr = cmsData.regex.getAttr(match, 'key').replace(/\./g, '-')
22
    template = template.replace(
23
      cmsData.regex.escapeTextToRegex(match[0], 'g'),
24
      ' data-abe-' + cmsData.regex.validDataAbe(getattr) + '="'  + getattr + '" ' + match[0]
25
    )
26
  }
27
28
  return template
29
}
30
31
export function addHasAbeAttr(text) {
32
  return text.replace('}}', ' has-abe=1}}')
33
}
34
35
export function getAbeAttributeData(match, text, htmlAttribute, abeTag) {
36
  var valueOfAttritube
37
  var key = cmsData.regex.getAttr(match, 'key')
38
  var getattr
39
  var res
40
41
  if (cmsData.regex.isSingleAbe(match, text)) {
42
    valueOfAttritube = key.replace(/\./g, '-')
43
    key = cmsData.regex.validDataAbe(valueOfAttritube)
44
    getattr = key.replace(/\./g, '-')
45
    res = ' data-abe-attr-' + valueOfAttritube + '="'  + htmlAttribute + '"' + ' data-abe-' + valueOfAttritube + '="'  + getattr + '"' + abeTag
46
  }else {
47
    var valueOfAttritube = key.split('.')
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable valueOfAttritube already seems to be declared on line 36. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
48
    var parentKey = valueOfAttritube.shift()
49
    valueOfAttritube = `${parentKey}[index].${valueOfAttritube[0]}`
50
    var valueOfAttritubeIndexed = valueOfAttritube.replace(/\[index\]/, '{{@index}}')
51
    key = cmsData.regex.validDataAbe(valueOfAttritube)
52
    getattr = key
53
54
    res = ` data-abe-attr-${valueOfAttritube}="${htmlAttribute}"  data-abe-${valueOfAttritube}="${getattr}"`
55
    + ` data-abe-attr-${valueOfAttritubeIndexed}="${htmlAttribute}" data-abe-${valueOfAttritubeIndexed}="${getattr}"${abeTag}`
56
  }
57
58
  return res
59
}
60
61
/**
62
 *
63
 * IF ABE TAG SINGLE (NOT ABE EACH STATEMENT)
64
 * 
65
 * THIS:
66
<img src="{{abe type='image' key='image_key' tab='default'}}" alt="">
67
68
 * BECOME:
69
<img data-abe-attr-image_key="src" data-abe-image_key="image_key" data-abe-attr-image_key="src"
70
data-abe-image_key="image_key" src="{{abe type='image' key='image_key' tab='default' has-abe=1 has-abe=1}}" alt="">
71
72
 *
73
 * IF ABE EACH TAG
74
 * THIS:
75
{{#each test}}
76
  <img src="{{abe type='image' key='test.img' desc='test_img' tab='default'}}" alt="">
77
{{/each}}
78
79
 * BECOME:
80
{{#each test}}
81
  <img data-abe-attr-test[index].img="src" data-abe-test[index].img="test[index].img" src="{{abe type='image' key='test.img' desc='test_img' tab='default' has-abe=1}}" alt="">
82
{{/each}}
83
84
 * @param {[type]} template [description]
85
 */
86
export function addAbeDataAttrForHtmlAttributes(template, key) {
0 ignored issues
show
Unused Code introduced by
The parameter key is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
87
  var text = template.replace(/<([A-Za-z]+)/g, '\nABE_SPLIT<$1')
88
  let abeTagIntoAttribute = text.match(cmsData.regex.abeAsAttributePattern)
89
90
  if (abeTagIntoAttribute != null) {
91
    Array.prototype.forEach.call(abeTagIntoAttribute, (abeIntoTag) => {
92
      let matchAbeTag = /({{abe.*?[\s\S].*?}})/g.exec(abeIntoTag)
93
94
      if(matchAbeTag != null && matchAbeTag[1] != null) {
95
        var toReplace = cmsTemplates.prepare.getAbeAttributeData(matchAbeTag[1], text, (abeIntoTag.split('=')[0]).trim(), abeIntoTag)
96
97
        toReplace = toReplace.replace(
98
          cmsData.regex.escapeTextToRegex(matchAbeTag[1]),
99
          cmsTemplates.prepare.addHasAbeAttr(matchAbeTag[1])
100
        )
101
102
        text = text.replace(
103
          cmsData.regex.escapeTextToRegex(abeIntoTag),
104
          toReplace
105
        )
106
      }
107
    })
108
  }
109
  text = text.replace(/\nABE_SPLIT</g, '<')
110
111
  return text
112
}
113
114
/**
115
 * Example:
116
 *
117
 *
118
 * THIS:
119
{{abe type='data' key='data_key' source='select title from article' display='title' editable='true' tab='default'}}
120
121
{{#each data_key}}
122
  {{title}}
123
{{/each}}
124
125
 *
126
 * BECOME THIS
127
128
{{abe type='data' key='data_key' source='select title from article' display='title' editable='true' tab='default'}}
129
130
{{#each data_key}}
131
  {{title}}
132
{{/each}}<!-- [[data_key]] %7B%7B%23each%20data_key%7D%7D%0A%09%7B%7Btitle%7D%7D%0A%7B%7B/each%7D%7D -->
133
134
 * @param {[type]} template [description]
135
 * @param {[type]} json     [description]
136
 */
137
export function addAbeSourceComment(template, json) {
138
  
139
  // Don't know what it does...
140
  if(typeof json.abe_source !== 'undefined' && json.abe_source !== null) {
141
    var keys = Object.keys(json.abe_source)
142
    
143
    for(var i in keys) {
0 ignored issues
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
144
      var replaceEach = new RegExp(`<!-- \\[\\[${keys[i]}\\]\\][\\s\\S]*?-->`, 'g')
145
      template = template.replace(replaceEach, '')
146
147
      var patAttrSource = new RegExp(' ([A-Za-z0-9\-\_]+)=["|\'].*?({{' + keys[i] + '}}).*?["|\']', 'g')
148
      var patAttrSourceMatch = template.match(patAttrSource)
149
150
      if(patAttrSourceMatch != null) {
151
        let checkEscapedRegex = /["|'](.*?)["|']/
152
        let patAttrSourceInside = new RegExp('(\\S+)=["\']?((?:.(?!["\']?\\s+(?:\\S+)=|[>"\']))+.)["\']?({{' + keys[i] + '}}).*?["|\']', 'g')
153
        Array.prototype.forEach.call(patAttrSourceMatch, (pat) => {
154
          let patAttrSourceCheck = patAttrSourceInside.exec(pat)
155
          if(patAttrSourceCheck != null) {
156
            
157
            let checkEscaped = checkEscapedRegex.exec(patAttrSourceCheck[0])
158
            if(checkEscaped != null && checkEscaped.length > 0) {
159
              checkEscaped = escape(checkEscaped[1])
160
              template = template.replace(
0 ignored issues
show
Bug introduced by
The variable template is changed as part of the for-each loop for example by template.replace(replaceEach, "") on line 145. Only the value of the last iteration will be visible in this function if it is called after the loop.
Loading history...
161
                patAttrSourceCheck[0],
162
                ` data-abe-attr="${patAttrSourceCheck[1]}" data-abe-attr-escaped="${checkEscaped}" data-abe="${keys[i]}" ${patAttrSourceCheck[0]}`
0 ignored issues
show
introduced by
The variable i is changed by the for-each loop on line 143. Only the value of the last iteration will be visible in this function if it is called outside of the loop.
Loading history...
163
              )
164
            }
165
          }
166
        })
167
      }
168
169
      var eachSource = new RegExp(`({{#each ${keys[i]}}[\\s\\S a-z]*?{{\/each}})`, 'g')
170
      var matches = template.match(eachSource)
171
      if(typeof matches !== 'undefined' && matches !== null) {
172
        Array.prototype.forEach.call(matches, (match) => {
173
          template = template.replace(match, `${match}<!-- [[${keys[i]}]] ${cmsTemplates.encodeAbeTagAsComment(match)} -->`)
0 ignored issues
show
introduced by
The variable i is changed by the for-each loop on line 143. Only the value of the last iteration will be visible in this function if it is called outside of the loop.
Loading history...
Bug introduced by
The variable template is changed as part of the for-each loop for example by template.replace(replaceEach, "") on line 145. Only the value of the last iteration will be visible in this function if it is called after the loop.
Loading history...
174
        })
175
      }
176
    }
177
  }
178
179
  return template
180
}
181
182
/**
183
 * THIS:
184
<span>{{abe type='text' key='text_visible'}}</span>
185
186
 * BECOME:
187
<span><abe>{{abe type='text' key='text_visible'}}</abe></span>
188
189
 * @param {[type]} template [description]
190
 */
191
export function addAbeHtmlTagBetweenAbeTags(template) {
192
  var match
193
  while (match = cmsData.regex.abePattern.exec(template)) {
194
    template = template.replace(cmsData.regex.escapeTextToRegex(match[1], 'g'), '<abe>' + match[1].trim() + '</abe>')
195
  }
196
197
  return template
198
}
199
200
/**
201
 * THIS:
202
[index].
203
204
 * BECOME:
205
{{@index}}-
206
207
 *  @param  {[type]} template [description]
208
 * @return {[type]}          [description]
209
 */
210
export function replaceAbeEachIndex(template) {
211
  return template.replace(/\[index\]\./g, '{{@index}}-')
212
}
213
214
export function removeHiddenAbeTag(template) {
215
  return template.replace(/(\{\{abe.*visible=[\'|\"]false.*\}\})/g, '')
216
}
217
218
/**
219
 * Remove {{abe type=*}} from html if attribute visible="false"
220
 * @param  {[type]} template [description]
221
 * @return {[type]}          [description]
222
 */
223
export function removeHandlebarsRawFromHtml(template) {
224
  return template.replace(/\{\{\{\{\/?raw\}\}\}\}/g, '')
225
}
226
227
/**
228
 * split {{#each}}...{{/each}} into an array
229
 * 
230
 * @param  {[type]} template [description]
231
 * @return {[type]}          [description]
232
 */
233
export function splitEachBlocks(template) {
234
  var block
235
  var blocks = []
236
237
  while (block = cmsData.regex.blockPattern.exec(template)) {
238
    blocks.push(block[1])
239
  }
240
241
  return blocks
242
}
243
244
export function indexEachBlocks(template, onlyHtml) {
245
  // create an array of {{each}} blocks
246
  var blocks = cmsTemplates.prepare.splitEachBlocks(template)
247
248
  Array.prototype.forEach.call(blocks, (block) => {
249
    var key = block.match(/#each (.*)\}\}/)[1]
250
    var match
251
252
    if(!onlyHtml) {
253
254
      var voidData = {}
255
      voidData[key] = [{}]
256
      var blockCompiled = Handlebars.compile(block.replace(/{{abe (.*?)}}/g, '[[abe $1]]').replace(new RegExp(`\\.\\.\/${config.meta.name}`, 'g'), config.meta.name))
257
      var blockHtml = blockCompiled(voidData, {data: {intl: config.intlData}}).replace(/\[\[abe (.*?)\]\]/g, '{{abe $1}}')
258
259
      // je rajoute un data-abe-block avec index sur tous les tags html du bloc each
260
      var textEachWithIndex = block.replace(/(<(?![\/])[A-Za-z0-9!-]*)/g, '$1 data-abe-block="' + key + '{{@index}}"')
261
262
      // je remplace le block dans le texte par ça
263
      template = template.replace(block, textEachWithIndex + `<!-- [[${key}]] ${cmsTemplates.encodeAbeTagAsComment(blockHtml)} -->`)
264
    }
265
266
    // Pour chaque tag Abe
267
    while (match = cmsData.regex.abeTag.exec(block)) {
268
      // template = cmsTemplates.prepare.insertAbeEach(template, match, key, cmsData.regex.eachBlockPattern.lastIndex - block.length, onlyHtml)
269
      template = cmsTemplates.prepare.addAbeDictionnary(template, match[0], key)
0 ignored issues
show
Bug introduced by
The variable template is changed as part of the while loop for example by cmsTemplates.prepare.add...template, match.0, key) on line 269. Only the value of the last iteration will be visible in this function if it is called after the loop.
Loading history...
270
    } 
271
  })
272
273
  return template
274
}
275
276
/**
277
 * split {{#each}}...{{/each}} into an array
278
 *
279
 * THIS:
280
  {{abe type='text' key='test.title' desc='test title' tab='default'}}
281
282
 * BECOME THIS:
283
  {{abe dictionnary='test' type='text' key='test.title' desc='test title' tab='default'}}
284
285
 * 
286
 * @param  {[type]} template [description]
287
 * @return {[type]}          [description]
288
 */
289
export function addAbeDictionnary(template, match, key) {
290
  if(cmsData.regex.isEachStatement(match)) return
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
291
292
  if(cmsData.regex.isBlockAbe(match)){
293
    var abeDictionnary = match.replace(new RegExp('(key=[\'|"])' + key + '.', 'g'), '$1' + key + '[index].')
294
                               .replace(/\{\{abe/, '{{abe dictionnary=\'' + key + '\'')
295
296
    template = template.replace(match, abeDictionnary)
297
  }
298
299
  return template
300
}